/* Gmaps : set new position on the map
 * @param lat,
 * @param lon
 * @param id of selected point in database
 * used in showSearchResult.php
 */
function SetPosition(lat, lon, id)
{
    if (map == null)
    {
        initGMap();
    }
    if (map != null)
    {//gdy zainicjalizowana mapa
        map.clearOverlays();
        desc = document.getElementById("d"+id).innerHTML
        name = document.getElementById("n"+id).innerHTML;
        var info ='<div class="dymek"><b>'+name+'</b><br>'+desc+'</div>';
        var point = new GLatLng(lat, lon);
        map.setCenter(point, 16);
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(info);
        });
        map.addOverlay(marker);
    }
}

function SetPosition2(i)
{
   marker = gmarkers[i] ;
   map.setCenter(marker.getPoint(),map.getZoom());
}
Array.prototype.clone = function () {
   var arr1 = new Array();
   for (var property in this) {
      arr1[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]
   }
   return arr1;
}

//Object.prototype.clone = function() {
//  var newObj = (this instanceof Array) ? [] : {};
//  for (i in this) {
//    if (i == 'clone') continue;
//    if (this[i] && typeof this[i] == "object") {
//      newObj[i] = this[i].clone();
//    } else newObj[i] = this[i]
//  } return newObj;
//};

function cloneObject(source) {
    for (i in source) {
        if (typeof source[i] == 'source') {
            this[i] = new cloneObject(source[i]);
        }
        else{
            this[i] = source[i];
	}
    }
}

function showCheckedPoints()
{
    var elements = document.getElementsByName('checkbox[]');
    var checked =new Array();
    var j = 0;
    for (var i=0; i<elements.length; i++)
    {
        if (elements[i].checked == true){
            checked[j++] = elements[i].value;
        }
    }
    if (checked.length == 0)
    {
        alert("Nie zaznaczyłeś żadnych punktów.");
        return;
    }
    if (map == null)
    {
        initGMap();
    }
    if (map != null)
    {//gdy zainicjalizowana mapa
        map.clearOverlays();
        bounds = new GLatLngBounds();
        //dodajemy wszytskie wybrane punkty
        
        for (i=0; i<checked.length; i++)
        {
            lon = document.getElementById("lon"+checked[i]).innerHTML;
            lat = document.getElementById("lat"+checked[i]).innerHTML;
            AddMarkerAndDesc(lat, lon, checked[i]);
        }
    }
}

function AddMarkerAndDesc(lat, lon, id)
{
    desc = document.getElementById("d"+id).innerHTML;
    name = document.getElementById("n"+id).innerHTML;
    var info ='<div class="dymek"><b>'+name+'</b><br>'+desc+'</div>';
    var point = new GLatLng(lat, lon);
    map.setCenter(point, 16);
    var marker = new GMarker(point);
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(info);
    });
    bounds.extend(point);
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(bounds.getCenter());
    map.addOverlay(marker);
}
function initGMap()
{
    divMap = document.getElementById('map');
    divMap.style.display = 'block';
    if (GBrowserIsCompatible()) {
        map = new GMap2(divMap);
        map.addControl(new GLargeMapControl());
        map.enableContinuousZoom();
    }
    else
    {
        divMap.innerHTML = "Przykro mi, Google Maps API nie jest kompatybilne z Twoją przeglądarką.";
    }
}
function AddSimpleMarker(lat, lon)
{
    var point = new GLatLng(lat, lon);
    map.setCenter(point, 16);
    var marker = new GMarker(point);
  //  bounds.extend(point);
   // map.setZoom(map.getBoundsZoomLevel(bounds));
   // map.setCenter(bounds.getCenter());
    map.addOverlay(marker);
}
var side_bar_html = "";
gmarkers = [];
var htmls = [];
var i = 0;

function addMarkerAndExtendedDesc(point,name,html,label, dystans) {
   var marker = new GMarker(point);
   GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(html + "<br>" +label + "<br> " +dystans+"km");
   });
   gmarkers[i] = marker;
   htmls[i] = html;
   side_bar_html += '<a href="javascript:SetPosition2(' + i + ')">' + name + '<\/a><br>';
   i++;
   return marker;
}

// A function to create the marker and set up the event window
function addMarkerAndExtendedDesc(_id, point,name,html,label, dystans, icontype) {
   // === create a marker with the requested icon ===
   //gicons[icontype] must be defined earlier
   var marker = new GMarker(point, { icon:gicons[icontype], id:_id});
   GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(html+ "<br>" +label + "<br> " +dystans+"km");
   });
   // save the info we need to use later for the side_bar

   gmarkers.push(marker );
   htmls.push( html);
 //  GLog.write('2 gmarkers.length ='+gmarkers.length);
   // add a line to the side_bar html
   side_bar_html += '<a href="javascript:SetPosition2(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
   return marker;
}

function addMarkerOnTrack(_id, point,name,desc) {
   var marker = new GMarker(point, {id:_id});
   GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml('<div class="dymek"><b>'+name+'</b><br>'+desc+'</div>');
   });
   return marker;
}


function reloadMap( cat, isOn )
{
   lon = map.getCenter().lng();
   lat = map.getCenter().lat();
   
   if (cat!=null && isOn!=null)
   {
      document.getElementById("btn"+cat).onclick = Function("reloadMap("+cat+","+ !isOn+ ")");
   }
 
   var ini = document.getElementById('ini').value;
   var inr = document.getElementById('inr').value;
   if(inr == "")
   {
      inr = 3;
   }
   if(ini == "")
   {
      ini = 5;
   }
   if (ini < 1)
      {
         alert("Maksymalna ilość punktów na mapie musi być wartością dodatnią!");
         return;
      }
   readMap('lon='+lon+'&'+'lat='+lat+'&r='+inr+'&i='+ini+'&c='+cat+'&on='+isOn);
   cross.setPoint(new GLatLng(lat,lon));
   map.addOverlay(cross);
}

//Create a GDirection object for all points current on map
//fills directions div with instructions
function generateDirection(seqArr)
{
   if (gmarkers.length > 0 )
   {
      var waypointsString = [];
      //GLog.write('gmarkers.length ='+gmarkers.length);
      if ( typeof seqArr == 'undefined')
      {//trasa pomiedzy gmarkers i cross
         for (var i=0 ; i<gmarkers.length; i++)
         {
            waypointsString[i] = gmarkers[i].getLatLng().toUrlValue()  ;
         }
         waypointsString.unshift(cross.getLatLng().toUrlValue());
      }
      else
      {//tryb z uwzglednieniem kolejnosci indeksow w tablicy seqArr
      //tylko tablica gmarkers
          for (var i=0 ; i<seqArr.length; i++)
         {
            waypointsString[i] = gmarkers[seqArr[i]].getLatLng().toUrlValue()  ;
         }
      }
      directions.loadFromWaypoints(waypointsString,{getPolyline:true,travelMode:G_TRAVEL_MODE_WALKING});
   }
   else
   {
      GLog.write('Brak markerow do wyznaczenia trasy!');
   }
}

function appendRow( elem, id, lat, lon, name, desc)
{
   var img = '<td><img alt="ShowOnMap" class="map_img" src="images/showmap_small.jpg" onClick="SetPosition('+ lat +', '+ lon +','+ id +' )"></td>';
   var text = '<td id="n'+ id +'">'+ name +'</td><td id="d'+ id +'">'+ desc +'</td></tr>';
   elem.innerHTML += '<tr><td><input type="checkbox" name="checkbox[]" id="'+id+'" value="'+id+'" /></td><td id="lon'+id+'">'+lon+'</td><td id="lat'+id+'">'+lat+'</td>'+img+text;
   //elem.innerHTML +=
}

function loadPointsEnd(MyRequest)
{
   var jsonData = eval("("+MyRequest.responseText+")");
   // hide the info window, otherwise it still stays open where the removed marker used to be
   // empty the array
   gmarkers.splice(0);
   gmarkers.length = 0;
   bounds = new GLatLngBounds();
   GLog.write('ilość obiektów w pliku json: ' +jsonData.length)
   for (var i = 0; i < jsonData.length; i++) {
      // obtain the attribues of each marker
      var point = new GLatLng(jsonData[i].lat, jsonData[i].lon);
       bounds.extend(point);
      var marker = addMarkerOnTrack(jsonData[i].id, point,jsonData[i].name,jsonData[i].desc);
      //GLog.write('dodano marker o id=' + marker.id);
      gmarkers.push(marker );
     // map.addOverlay(marker);
   }
   refreshTrack();
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(bounds.getCenter());
}
function refreshTrack(){
   arr = Sortable.sequence("list");
   generateDirection(arr);
   
}